package cn.edu.swust.adressbook.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 汉字转拼音
 */
public class PinyinUtil {

    public static String getPingYin(String src) {

        char[] srcCharArray;
        srcCharArray = src.toCharArray();
        String[] newString;
        HanyuPinyinOutputFormat pinyinOutputFormat = new HanyuPinyinOutputFormat();

        pinyinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        pinyinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        pinyinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
        String result = "";
        int t0 = srcCharArray.length;
        try {
            for (int i = 0; i < t0; i++) {
                // 判断是否为汉字字符
                if (java.lang.Character.toString(srcCharArray[i]).matches(
                        "[\\u4E00-\\u9FA5]+")) {
                    newString = PinyinHelper.toHanyuPinyinStringArray(srcCharArray[i], pinyinOutputFormat);
                    result += newString[0];
                } else
                    result += java.lang.Character.toString(srcCharArray[i]);
            }
            // System.out.println(t4);
            return result.toLowerCase();
        } catch (BadHanyuPinyinOutputFormatCombination e1) {
            e1.printStackTrace();
        }
        return result.toLowerCase();
    }
}
